package com.winchain.chainbill.basic.invoice.rx;

import com.shell.bee.invoince.po.InvDfr;
import com.shell.bee.invoince.service.InvDfrService;
import com.shell.constant.rel.AssetCode;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.shell.framework.utils.CommonDataUtil;
import com.shell.framework.utils.MessageSender;
import com.shell.framework.utils.SysDateUtil;
import com.shell.governor.modules.message.keyword.InvoiceOverdueUploadRestoreQuotaKeyWord;
import com.winchain.chainbill.bill.base.dao.CbDctDao;
import com.winchain.chainbill.bill.base.po.CbDct;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.base.po.CbSnd;
import com.winchain.chainbill.bill.base.service.CbRecService;
import com.winchain.chainbill.bill.base.service.CbSndService;
import com.winchain.chainbill.bill.biz.Bill;
import com.winchain.chainbill.bill.biz.BillEvent;
import com.winchain.chainbill.trade.service.BillAcctBlcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillInvoiceDfrOverdueUploadSubscriber
		extends OnErrorNotImplementedSubscriber<BillEvent<? extends Object>> {
	@Autowired
	private InvDfrService invDfrService;
	@Autowired
	private CbRecService cbRecService;
	@Autowired
	private CbSndService cbSndService;
	@Autowired
	private CbDctDao cbDctDao;
	@Autowired
	private BillAcctBlcService billAcctBlcService;

	public void onApplicationEvent(BillEvent<? extends Object> t) {
		Object source = t.getBill().getSource();
		if (source == null) {
			return;
		}
		CbDct dct = (CbDct) source;
		InvDfr invDfr = this.invDfrService.selectByBiz(dct.getDctId(), "1");
		boolean overdue = this.invDfrService.isOverdue(invDfr);
		if (overdue) {
			CbRec rec = (CbRec) this.cbRecService.selectByKey(dct.getBillId());
			CbSnd snd = this.cbSndService.getBillSndById(rec.getRootId());
			int count = this.cbDctDao.countOverdueUploadInvoice(snd.getBuyerId(), SysDateUtil.getSystemDate());
			if (count == 0) {
				this.billAcctBlcService.updateAcctBkpState(dct.getFinId(), snd.getBuyerId(), AssetCode.FQT.name(), "42",
						"1");

				String template = "MT05001";
				InvoiceOverdueUploadRestoreQuotaKeyWord keyWord = new InvoiceOverdueUploadRestoreQuotaKeyWord();
				String sendId = CommonDataUtil.getUserId();
				MessageSender.sendMessageByTmpl(sendId, template, keyWord, snd.getBuyerId());
			}
		}
	}
}
